iT邦幫忙

2022 iThome 鐵人賽

DAY 26
1
Software Development

30天學習.Net MAUI系列 第 26

26.MAUI使用firebase進行Auth (三)

  • 分享至 

  • xImage
  •  

今天我們試著加入登入功能

新增Service功能

打開Todo\Services\IAuthService.cs加入login

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Todo.Models;

namespace Todo.Services
{
    public interface IAuthService
    {
        Task<bool> RegisterUserWithEmail(UserModel user);
        Task<bool> LoginUserWithEmail(UserModel user);
    }
}

打開AuthService.cs加入

using Firebase.Auth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Todo.Models;

namespace Todo.Services
{
    public class AuthService : IAuthService
    {
        private readonly String webApikey = ".................o"; // Type your web api key

        public async Task<bool> LoginUserWithEmail(UserModel user)
        {
            try {
                var authProvider = new FirebaseAuthProvider(new FirebaseConfig(webApikey));
                var auth = await authProvider.SignInWithEmailAndPasswordAsync(user.email, user.password);

                return true;
            } catch {
                return false;
            }
        }

        public async Task<bool> RegisterUserWithEmail(UserModel user)
        {
            try {
                var authProvider = new FirebaseAuthProvider(new FirebaseConfig(webApikey));
                var auth = await authProvider.CreateUserWithEmailAndPasswordAsync(user.email, user.password);

                return true;
            } catch {
                return false;
            }

        }
    }
}

新增ViewModel功能

打開Todo\ViewModels\AuthViewModel.cs

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Todo.Models;
using Todo.Services;

namespace Todo.ViewModels
{
    [QueryProperty(nameof(User), "User")]
    public partial class AuthViewModel : ObservableObject
    {
        [ObservableProperty]
        private UserModel _user = new UserModel();
        private readonly IAuthService _authService;
        public AuthViewModel(IAuthService authService)
        {
            _authService = authService;
        }

        [RelayCommand]
        public async void LoginUserWithEmailAndPassword()
        {
            var result = await _authService.LoginUserWithEmail(new Models.UserModel
            {
                email=User.email,
                password=User.password,
            });
            if (result) {
                await Shell.Current.DisplayAlert("Status: Login Success", "Login Success", "Ok");
            } else {
                await Shell.Current.DisplayAlert("Status: Login Failed", "Login failed", "Ok");
            }
        }

        [RelayCommand]
        public async void RegisterUserWithEmailAndPassword()
        {
            var result = await _authService.RegisterUserWithEmail(new Models.UserModel
            {
                email=User.email,
                password=User.password,
            });
            if (result) {
                await Shell.Current.DisplayAlert("Status: Register Success", "User registed", "Ok");
            } else {
                await Shell.Current.DisplayAlert("Status: Register Failed", "Something is failed", "Ok");
            }
        }
    }
}

註冊Views到MauiProgram

打開Todo\MauiProgram.cs並加入

builder.Services.AddSingleton<AuthPage>();

MauiProgram.cs

using Todo.Services;
using Todo.ViewModels;

namespace Todo;

public static class MauiProgram
{
	public static MauiApp CreateMauiApp()
	{
		var builder = MauiApp.CreateBuilder();
		builder
			.UseMauiApp<App>()
			.ConfigureFonts(fonts =>
			{
				fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
				fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
			});

		// Add TodoItem Service
		builder.Services.AddSingleton<ITodoService, TodoService>();
		builder.Services.AddSingleton<IAuthService, AuthService>();

		// Add Views
		builder.Services.AddSingleton<AddTodoPage>();
        builder.Services.AddSingleton<TodoPage>();
		builder.Services.AddSingleton<RegisterPage>();
		builder.Services.AddSingleton<AuthPage>();

        // Add ViewModel
        builder.Services.AddSingleton<TodoListViewModel>();
		builder.Services.AddSingleton<AddUpdateTodoViewModel>();
		builder.Services.AddSingleton<AuthViewModel>();

		return builder.Build();
	}
}

加入到Page

打開Todo\Pages\AuthPage.xaml.cs

using Todo.ViewModels;

namespace Todo;

public partial class AuthPage : ContentPage
{
	public AuthPage(AuthViewModel vm)
	{
		InitializeComponent();
        this.BindingContext = vm;
    }

    private async void RegisterRoute(object sender, EventArgs e)
    {
        await AppShell.Current.GoToAsync(nameof(RegisterPage));
    }
}

打開Todo\Pages\AuthPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:models="clr-namespace:Todo.Models"
             xmlns:viewModels="clr-namespace:Todo.ViewModels"
             x:DataType="viewModels:AuthViewModel"
             x:Class="Todo.AuthPage"
             Title="AuthPage">
    <VerticalStackLayout>
        <Entry Placeholder="Email" Text="{Binding User.email}" />
        <Entry Placeholder="Password" Text="{Binding User.password}" IsPassword="true" />

        <Button Text="Login" Command="{Binding LoginUserWithEmailAndPasswordCommand}" />

        <HorizontalStackLayout>
            <Label Text="No Account?" />
            <Button Text="Register" Clicked="RegisterRoute"/>
        </HorizontalStackLayout>
    </VerticalStackLayout>
</ContentPage>

測試
https://ithelp.ithome.com.tw/upload/images/20221011/20108931sN7h8ssxaa.png
https://ithelp.ithome.com.tw/upload/images/20221011/201089316R4maCRNiL.png


今天簡單的實現了登入功能,明天會完善Auth功能,包含登入以及獲取token等等,明天見。


上一篇
25.MAUI使用firebase進行Auth (二)
下一篇
27.MAUI使用firebase進行Auth (四)
系列文
30天學習.Net MAUI30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言